package com.jiemengshi.server.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jiemengshi.server.model.UserWechat;
import com.jiemengshi.server.util.*;
import org.apache.http.HttpException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by MingQi on 2017/10/14.
 */
@Service
public class WechatService {
    @Autowired
    private WechatUserService userService;
    
    @Value("${wx_dream_reply_inform_template}")
    private String dreamReplyInformTemplate;

    private Cache tokenCache;

    private Map<String, String> wxAppIds = new HashMap<>();
    private Map<String, String> wxSerects = new HashMap<>();
    
    @Autowired
    public WechatService(EhCacheCacheManager cacheManager) {
        tokenCache = cacheManager.getCache("token");

        wxAppIds.put("jms", "wx83e2f79a33be95d0");
        wxSerects.put("jms", "3d41c836df148057adbe0d5bdae09163");

        wxAppIds.put("zgjm", "wx0b636254e37d879d");
        wxSerects.put("zgjm", "5aa1a6ec22e14a659bde2a17d3f11e66");
    }
    
    private JSONObject getSessionKeyAndIdByCode(String code, String appName) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + wxAppIds.get(appName) + "&secret=" + wxSerects.get(appName) + "&js_code=" + code + "&grant_type=authorization_code";
        JSONObject ret = JSONObject.parseObject(ApiHttp.doGet(url));
        
        return ret;
    }

    public String getOpenIdByCode(String code, String appName) throws PrjException {
        JSONObject requestRet = getSessionKeyAndIdByCode(code, appName);
        
        if(requestRet.getIntValue("errcode") > 0)
            throw new PrjException(ErrorCodeMsg.USER_WECHAT_LOGIN_CODE_ERROR);

        String openId = requestRet.getString("openid");
        if(StringUtil.isEmpty(openId))
            throw new PrjException(ErrorCodeMsg.USER_WECHAT_LOGIN_CODE_ERROR);
        
        return appName + "-" + openId;
    }

    public String getAccessToken(String appName) throws HttpException, IOException {
        String key = "accessToken";

        String accessToken = tokenCache.get(key, String.class);
        if (!StringUtil.isEmpty(accessToken)) {
            return accessToken;
        }

        // 获取accessToken start
        String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                + wxAppIds.get(appName) + "&secret=" + wxSerects.get(appName);
        String responseJsonData = ApiHttp.doGet(accessTokenUrl);
        JSONObject jsonData = JSON.parseObject(responseJsonData);
        accessToken = jsonData.getString("access_token");

        if (!StringUtil.isEmpty(accessToken)) {
            tokenCache.put(key, accessToken);
        }

        return accessToken;
    }

    public boolean sendDreamReplyInformTemplateMsg(int userId, String appName, String keyword1) throws HttpException, IOException{
        UserWechat toUserWechat = userService.getUserWechatById(userId);
        String formId = userService.consumeFormId(toUserWechat.getId());
        if(StringUtil.isEmpty(formId))
            return false;
        
        String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="+getAccessToken(appName);

        JSONObject input = new JSONObject();
        input.put("touser", toUserWechat.getWechatOpenId());

        JSONObject data = new JSONObject();
        input.put("template_id", dreamReplyInformTemplate);
        input.put("emphasis_keyword", "keyword2.DATA");
        input.put("page", "pages/mengjingku/mengjingku");
        input.put("form_id", formId);

        JSONObject k1 = new JSONObject();
        k1.put("value", keyword1);
        k1.put("color", "#173177");
        data.put("keyword1", k1);

        JSONObject keyword2 = new JSONObject();
        keyword2.put("value", "您有新回复");
        keyword2.put("color", "#173177");
        data.put("keyword2", keyword2);

        JSONObject keyword3 = new JSONObject();
        keyword3.put("value", DateUtil.getCurrentTime());
        keyword3.put("color", "#173177");
        data.put("keyword3", keyword3);

        input.put("data", data);

        JSONObject ret = ApiHttp.doPostJsonData(url, input, null);
        return ret.getIntValue("errcode") == 0;
    }
}
